/**
 * TManViewUpdater.java
 * ************************** 
 * @date Jun 1, 2011
 * @author Michele Tamburini
 * 
 * **************************
 */
package infrastructureAPI.algorithms.instanceTools.facilities;

import gossipServices.basic.nodeDescriptors.ConcreteNodeDescriptor;
import gossipServices.basic.nodeDescriptors.NodeDescriptor;
import gossipServices.basic.view.PartialView;
import gossipServices.bootstraping.tman.TManService;
import infrastructureAPI.Requester;
import infrastructureAPI.Service;
import infrastructureAPI.APIMessages.DispatcherRequestMessage;
import infrastructureAPI.APIMessages.RequestMessage;
import infrastructureAPI.algorithms.GeneralAPIFunctionAlgorithm;

import java.net.InetAddress;
import java.util.List;
import java.util.Vector;

/**
 * Description: 
 *
 */
public class TManViewNodeRemover extends GeneralAPIFunctionAlgorithm {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	protected Requester requester;
	protected List<NodeDescriptor> nodesToRemove;
	
	public TManViewNodeRemover(Requester requester, 
			List<NodeDescriptor> nodes){ 
		this.requester = requester;
		nodesToRemove = nodes;
	}

	@Override
	public RequestMessage createRequestMessage(InetAddress targetAddress,
			String targetNodeName) {
		return new DispatcherRequestMessage(
				new ConcreteNodeDescriptor(targetNodeName, targetAddress, null),
				this, requester);
	}

	@Override
	public Service extractServiceToDeRegister() {
		return null;
	}

	@Override
	public Service extractSuppliedService() {
		return null;
	}

	@Override
	public boolean requireSystemDeRegistration() {
		return false;
	}

	@Override
	public boolean requireSystemRegistration() {
		return false;
	}

	@Override
	public List<Class<?>> requiredServices() {
		List<Class<?>> list = new Vector<Class<?>>();
		list.add(TManService.class);
		return list;
	}

	@Override
	public boolean requireReply() {
		return false;
	}

	@Override
	public void run() {
		boolean ret = true;
		
		TManService tman = (TManService) services.get(0);
		
		PartialView view = tman.getOverlayNeighbors();
		
		System.out.println(this.getClass().getSimpleName()+
				" removing nodes from actual TMan overlay: ");
		synchronized (view) {			
			for(NodeDescriptor node : nodesToRemove){
				ret &= view.remove(view.find(node.getNodeName()));
				System.out.println("removed "+node+": "+ret);
			}
		}
//		System.out.println("New view is:\n"+view);
		
		// now we have to restart TMan in order to update the overlay
		tman.restartTMan(view);
		
		returnValue = ret;
	}

}
